<?php
/**
 * run with command 
 * php start.php start
 */

ini_set('display_errors', 'on');
use Workerman\Worker;
require_once __DIR__ . '/vendor/workerman/workerman/Autoloader.php';
require_once __DIR__ . '/vendor/workerman/mysql-master/src/Connection.php';

// 创建一个Worker监听2345端口，使用websocket协议通讯
$ws_worker = new Worker("websocket://0.0.0.0:2345");
// 启动1个进程对外提供服务
$ws_worker->count = 1;
// 新增加一个属性，用来保存uid到connection的映射(uid是用户id或者客户端唯一标识)
$ws_worker->uidConnections = array();
// 调用Mysql
$ws_worker->onWorkerStart = function($ws_worker) {
    // 将db实例存储在全局变量中(也可以存储在某类的静态成员中)
    global $db;
    $db = new Workerman\MySQL\Connection('127.0.0.1', '3306', 'root', '', 'join');
};
// 当收到客户端发来的数据后返回给客户端
$ws_worker->onMessage = function($connection, $data){
    global $db;
    global $ws_worker;

    list($uid,$oid) = explode(',',$data);
    // 保存uid到connection的映射
    $connection->uid = $uid;
    $ws_worker->uidConnections[$connection->uid] = $connection;

    // app客户端触发传递订单号，推送给后台商家
    if($oid){
        $info = $db->query("select * from it_order where id = ".$oid);
        $uid  = $info[0]['bid'];
        $info = json_encode($info);
        // 给特定uid发送
        sendMessageByUid($uid,$info);
    }
};

// 针对uid推送数据
function sendMessageByUid($uid,$info){
    global $ws_worker;
    if(isset($ws_worker->uidConnections[$uid])) {
        $connection = $ws_worker->uidConnections[$uid];
        $connection->send($info);
    }
}

// 运行worker
Worker::runAll();